package br.com.news.rss;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import br.com.news.utils.database.beans.CategoriaBean;
import br.com.news.utils.database.beans.FonteBean;
import br.com.news.utils.database.beans.NoticiaBean;
import br.com.news.utils.database.beans.UsuarioBean;
import br.com.news.utils.service.exception.ServiceException;

public class RSSReader {
	private static RSSReader instance = null;
	private static final Logger logger = Logger.getLogger("RSSReader");

	public RSSReader() {
	}

	public static RSSReader getInstance() {
		if (instance == null) {
			instance = new RSSReader();
		}
		return instance;
	}

	public void writeNews() {

		try {

			List<CategoriaBean> categorias;
			categorias = RmiFactory.getCategoriaService()
					.findCategoriaByStatus(true);

			for (CategoriaBean categoria : categorias) {

				gravarNoticia(getItensRss(categoria.getUrlRss()),categoria);

			}

		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
		}
	}

	public Document getItensRss(String url) {
		try {
			DocumentBuilder builder;

			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

			URL u = new URL(url); // your feed url
			return builder.parse(u.openStream());
		} catch (ParserConfigurationException e) {
			logger.error(e.getMessage(),e);
		} catch (MalformedURLException e) {
			logger.error(e.getMessage(),e);
		} catch (SAXException e) {
			logger.error(e.getMessage(),e);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
		return null;
	}

	public void gravarNoticia(Document doc,CategoriaBean categoria) {
		NodeList nodes = doc.getElementsByTagName("item");

		try {

			Calendar dataFinal = Calendar.getInstance();
			dataFinal.add(Calendar.MINUTE, 5);

			int contador = 0;

			for (int i = 0; i < nodes.getLength(); i++) {

				Calendar dataAtual = Calendar.getInstance();

				if (dataAtual.after(dataFinal) || contador == 5) {
					contador = 0;
					break;
				}

				Element element = (Element) nodes.item(i);
				NoticiaBean noticia = new NoticiaBean();

				StringBuffer s;
				
					s = new StringBuffer(UrlTest.readLink(new URL(getElementValue(element, "link").trim())));

					StringBuffer imagem	= new StringBuffer(getElementValue(element, "description").trim());
					
					String imagemTexto = UrlTest.getImagem(imagem.toString());

				System.out.println("Title: "
						+ getElementValue(element, "title"));
				System.out.println("Titulo: " + UrlTest.getTitulo(s));

				
				noticia.setDataCriacao(new Date());
				noticia.setDataNoticia(new Date(getElementValue(element,"pubDate")));
				noticia.setStatus(true);
				
				String textoNoticia = UrlTest.getTexto(s);
				
				if (StringUtils.countMatches(textoNoticia, "</div>") > 10) break;
				
				noticia.setTexto(textoNoticia);
				
		    	String[] qnt = UrlTest.getTitulo(s).trim().split("               ");
		    	if (qnt.length >1) {
			    	try {
			    		
						noticia.setSubTitulo(ConvertUtil.toUTF8(qnt[1]));
						noticia.setTitulo(ConvertUtil.toUTF8(qnt[0]));
					} catch (Exception e) {
						logger.error(e.getMessage(),e);
					}
			    	
		    	} else {
		    		noticia.setTitulo(ConvertUtil.toUTF8(UrlTest.getTitulo(s)));
		    	}
				
				noticia.setUsuario(new UsuarioBean("alexandre", "Alexandre"));
				noticia.setUrl(getElementValue(element, "link").trim());
				
				
				FonteBean fonte = RmiFactory.getFonteService().buscaPorNome("Globo");
				noticia.setFonte(fonte);
				noticia.setCategoria(categoria);
				
				if (imagemTexto != null && !imagemTexto.equals("")) {
					noticia.setImagem(imagemTexto);
				}

				if (!noticia.getTitulo().equals("") && !RmiFactory.getNoticiaService().existeNoticia(noticia)) {

					RmiFactory.getNoticiaService().save(noticia);

				} else {
					contador++;
				}
			}

		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
		}  catch (MalformedURLException e) {
			logger.error(e.getMessage(),e);
		}
	}

	private String getCharacterDataFromElement(Element e) {
		try {
			Node child = e.getFirstChild();
			if (child instanceof CharacterData) {
				CharacterData cd = (CharacterData) child;
				return cd.getData();
			}
		} catch (Exception ex) {

		}
		return "";
	} // private String getCharacterDataFromElement

	protected float getFloat(String value) {
		if (value != null && !value.equals("")) {
			return Float.parseFloat(value);
		}
		return 0;
	}

	protected String getElementValue(Element parent, String label) {
		return getCharacterDataFromElement((Element) parent
				.getElementsByTagName(label).item(0));
	}

	public static void main(String[] args) {
		RSSReader reader = RSSReader.getInstance();
		reader.writeNews();
	}

}
